#include <iostream>
#include <string>
#include <vector>

#include "Thrad.hpp"
int tickets = 100;

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void *getTickets(void *args)
{
    std::string name = static_cast<const char *>(args);
    while (true)
    {
        //对临界区进行加锁
        pthread_mutex_lock(&mutex);
        pthread_mutex_lock(&mutex);
        if (tickets > 0)
        {
            usleep(1000); // 模拟抢票花费的时间

            std::cout << name << "正在抢票,抢到的票编号是:" << tickets << std::endl;
            tickets--;
            //对临界区解锁
            pthread_mutex_unlock(&mutex);
        }
        else
        {
            std::cout << "无票可抢!" << std::endl;
            pthread_mutex_unlock(&mutex);
            break;
        }
    }
    return nullptr;
}

int main()
{
    Thread thread1(getTickets, (void *)"thread 1", 0);
    Thread thread2(getTickets, (void *)"thread 2", 0);
    Thread thread3(getTickets, (void *)"thread 3", 0);
    Thread thread4(getTickets, (void *)"thread 4", 0);

    thread1.start();
    thread2.start();
    thread3.start();
    thread4.start();

    thread1.join();
    thread2.join();
    thread3.join();
    thread4.join();

    return 0;
}